using System;
using System.Collections.Generic;
using UnityEngine;

namespace GenerativeAgents.Unity
{
    /// <summary>
    /// 环境瓦片数据结构
    /// 表示环境中的一个瓦片单元
    /// </summary>
    [System.Serializable]
    public class EnvironmentTile
    {
        [Header("瓦片位置")]
        public Vector2Int gridPosition;      // 网格坐标
        public Vector3 worldPosition;        // 世界坐标
        
        [Header("瓦片属性")]
        public TileType tileType;            // 瓦片类型
        public bool isAccessible;            // 是否可访问
        public float movementCost = 1f;      // 移动成本
        
        [Header("瓦片内容")]
        public List<string> agents;          // 瓦片内的智能体
        public List<string> objects;         // 瓦片内的对象
        public List<string> events;          // 瓦片内的事件
        
        [Header("瓦片状态")]
        public DateTime lastUpdateTime;      // 最后更新时间
        public bool isDirty;                 // 是否需要更新
        public Dictionary<string, object> metadata; // 元数据
        
        [Header("视觉表示")]
        public GameObject visualObject;      // 视觉对象引用
        public Color tileColor = Color.white; // 瓦片颜色
        
        public EnvironmentTile()
        {
            agents = new List<string>();
            objects = new List<string>();
            events = new List<string>();
            metadata = new Dictionary<string, object>();
            lastUpdateTime = DateTime.Now;
            isAccessible = true;
        }
        
        /// <summary>
        /// 添加智能体到瓦片
        /// </summary>
        public void AddAgent(string agentName)
        {
            if (!agents.Contains(agentName))
            {
                agents.Add(agentName);
                isDirty = true;
                lastUpdateTime = DateTime.Now;
            }
        }
        
        /// <summary>
        /// 从瓦片移除智能体
        /// </summary>
        public void RemoveAgent(string agentName)
        {
            if (agents.Remove(agentName))
            {
                isDirty = true;
                lastUpdateTime = DateTime.Now;
            }
        }
        
        /// <summary>
        /// 添加对象到瓦片
        /// </summary>
        public void AddObject(string objectName)
        {
            if (!objects.Contains(objectName))
            {
                objects.Add(objectName);
                isDirty = true;
                lastUpdateTime = DateTime.Now;
            }
        }
        
        /// <summary>
        /// 从瓦片移除对象
        /// </summary>
        public void RemoveObject(string objectName)
        {
            if (objects.Remove(objectName))
            {
                isDirty = true;
                lastUpdateTime = DateTime.Now;
            }
        }
        
        /// <summary>
        /// 添加事件到瓦片
        /// </summary>
        public void AddEvent(string eventDescription)
        {
            events.Add(eventDescription);
            isDirty = true;
            lastUpdateTime = DateTime.Now;
        }
        
        /// <summary>
        /// 清理过期事件
        /// </summary>
        public void CleanupExpiredEvents(TimeSpan maxAge)
        {
            // 简化实现：清空所有事件
            if (events.Count > 0)
            {
                events.Clear();
                isDirty = true;
            }
        }
        
        /// <summary>
        /// 获取瓦片描述
        /// </summary>
        public string GetDescription()
        {
            var desc = $"{tileType} tile";
            
            if (agents.Count > 0)
            {
                desc += $" with {agents.Count} agent(s)";
            }
            
            if (objects.Count > 0)
            {
                desc += $" and {objects.Count} object(s)";
            }
            
            return desc;
        }
        
        /// <summary>
        /// 检查瓦片是否为空
        /// </summary>
        public bool IsEmpty()
        {
            return agents.Count == 0 && objects.Count == 0 && events.Count == 0;
        }
    }
    
    /// <summary>
    /// 瓦片类型枚举
    /// </summary>
    public enum TileType
    {
        CentralArea,        // 中央区域
        ResidentialArea,    // 住宅区域
        CommercialArea,     // 商业区域
        OutdoorArea,        // 户外区域
        SpecialArea,        // 特殊区域
        Obstacle,           // 障碍物
        Water,              // 水域
        Road               // 道路
    }
    
    /// <summary>
    /// 瓦片组件
    /// 附加到瓦片游戏对象上的组件
    /// </summary>
    public class TileComponent : MonoBehaviour
    {
        [Header("瓦片引用")]
        [SerializeField] private EnvironmentTile tileData;
        
        [Header("视觉设置")]
        [SerializeField] private Renderer tileRenderer;
        [SerializeField] private Material[] tileTypeMaterials;
        [SerializeField] private bool showDebugInfo = false;
        
        [Header("交互设置")]
        [SerializeField] private bool isInteractable = true;
        [SerializeField] private float interactionRange = 2f;
        
        // 内部状态
        private Color originalColor;
        private bool isHighlighted = false;
        
        private void Awake()
        {
            // 获取渲染器
            if (tileRenderer == null)
            {
                tileRenderer = GetComponent<Renderer>();
            }
            
            if (tileRenderer != null)
            {
                originalColor = tileRenderer.material.color;
            }
        }
        
        private void Start()
        {
            UpdateVisualRepresentation();
        }
        
        private void Update()
        {
            if (tileData != null && tileData.isDirty)
            {
                UpdateVisualRepresentation();
                tileData.isDirty = false;
            }
        }
        
        /// <summary>
        /// 初始化瓦片组件
        /// </summary>
        public void Initialize(EnvironmentTile tile)
        {
            tileData = tile;
            UpdateVisualRepresentation();
        }
        
        /// <summary>
        /// 更新视觉表示
        /// </summary>
        private void UpdateVisualRepresentation()
        {
            if (tileData == null) return;
            
            try
            {
                // 更新材质
                UpdateTileMaterial();
                
                // 更新颜色
                UpdateTileColor();
                
                // 更新名称
                gameObject.name = $"Tile_{tileData.gridPosition.x}_{tileData.gridPosition.y}_{tileData.tileType}";
            }
            catch (Exception ex)
            {
                Debug.LogError($"[TileComponent] Error updating visual representation: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 更新瓦片材质
        /// </summary>
        private void UpdateTileMaterial()
        {
            if (tileRenderer != null && tileTypeMaterials != null && tileTypeMaterials.Length > 0)
            {
                int materialIndex = (int)tileData.tileType % tileTypeMaterials.Length;
                if (materialIndex < tileTypeMaterials.Length && tileTypeMaterials[materialIndex] != null)
                {
                    tileRenderer.material = tileTypeMaterials[materialIndex];
                }
            }
        }
        
        /// <summary>
        /// 更新瓦片颜色
        /// </summary>
        private void UpdateTileColor()
        {
            if (tileRenderer == null) return;
            
            Color targetColor = tileData.tileColor;
            
            // 根据瓦片内容调整颜色强度
            if (tileData.agents.Count > 0)
            {
                targetColor = Color.Lerp(targetColor, Color.red, 0.3f);
            }
            
            if (tileData.objects.Count > 0)
            {
                targetColor = Color.Lerp(targetColor, Color.blue, 0.2f);
            }
            
            if (!tileData.isAccessible)
            {
                targetColor = Color.Lerp(targetColor, Color.black, 0.5f);
            }
            
            tileRenderer.material.color = targetColor;
        }
        
        /// <summary>
        /// 高亮瓦片
        /// </summary>
        public void Highlight(Color highlightColor)
        {
            if (tileRenderer != null && !isHighlighted)
            {
                originalColor = tileRenderer.material.color;
                tileRenderer.material.color = highlightColor;
                isHighlighted = true;
            }
        }
        
        /// <summary>
        /// 取消高亮
        /// </summary>
        public void RemoveHighlight()
        {
            if (tileRenderer != null && isHighlighted)
            {
                tileRenderer.material.color = originalColor;
                isHighlighted = false;
            }
        }
        
        /// <summary>
        /// 鼠标点击事件
        /// </summary>
        private void OnMouseDown()
        {
            if (isInteractable && tileData != null)
            {
                Debug.Log($"Clicked tile: {tileData.GetDescription()}");
                
                // 触发瓦片点击事件
                OnTileClicked();
            }
        }
        
        /// <summary>
        /// 鼠标悬停事件
        /// </summary>
        private void OnMouseEnter()
        {
            if (isInteractable && showDebugInfo)
            {
                Highlight(Color.yellow);
            }
        }
        
        /// <summary>
        /// 鼠标离开事件
        /// </summary>
        private void OnMouseExit()
        {
            if (isInteractable && showDebugInfo)
            {
                RemoveHighlight();
            }
        }
        
        /// <summary>
        /// 瓦片点击处理
        /// </summary>
        private void OnTileClicked()
        {
            // 可以在这里添加瓦片点击的具体逻辑
            // 例如：选择目标位置、显示信息等
        }
        
        /// <summary>
        /// 获取瓦片数据
        /// </summary>
        public EnvironmentTile GetTileData()
        {
            return tileData;
        }
        
        /// <summary>
        /// 设置交互性
        /// </summary>
        public void SetInteractable(bool interactable)
        {
            isInteractable = interactable;
        }
        
        /// <summary>
        /// 显示调试信息
        /// </summary>
        private void OnDrawGizmosSelected()
        {
            if (tileData == null) return;
            
            // 绘制瓦片边界
            Gizmos.color = tileData.isAccessible ? Color.green : Color.red;
            Gizmos.DrawWireCube(transform.position, Vector3.one);
            
            // 绘制交互范围
            if (isInteractable)
            {
                Gizmos.color = Color.yellow;
                Gizmos.DrawWireSphere(transform.position, interactionRange);
            }
        }
    }
    
    /// <summary>
    /// 环境区域
    /// 定义环境中的特定区域
    /// </summary>
    [System.Serializable]
    public class EnvironmentArea
    {
        [Header("区域属性")]
        public string areaName;              // 区域名称
        public AreaType areaType;            // 区域类型
        public Bounds bounds;                // 区域边界
        public string description;           // 区域描述
        public bool isAccessible = true;     // 是否可访问
        
        [Header("区域特性")]
        public List<string> availableActions; // 可用行动
        public Dictionary<string, object> properties; // 区域属性
        public Color areaColor = Color.white; // 区域颜色
        
        public EnvironmentArea()
        {
            availableActions = new List<string>();
            properties = new Dictionary<string, object>();
        }
        
        /// <summary>
        /// 初始化区域
        /// </summary>
        public void Initialize()
        {
            // 基于区域类型设置默认属性
            SetupDefaultProperties();
        }
        
        /// <summary>
        /// 设置默认属性
        /// </summary>
        private void SetupDefaultProperties()
        {
            switch (areaType)
            {
                case AreaType.Commercial:
                    availableActions.AddRange(new[] { "shop", "eat", "socialize" });
                    areaColor = Color.blue;
                    break;
                    
                case AreaType.Residential:
                    availableActions.AddRange(new[] { "rest", "sleep", "work_from_home" });
                    areaColor = Color.green;
                    break;
                    
                case AreaType.Outdoor:
                    availableActions.AddRange(new[] { "walk", "exercise", "relax", "explore" });
                    areaColor = Color.yellow;
                    break;
                    
                case AreaType.Entertainment:
                    availableActions.AddRange(new[] { "play", "watch", "listen", "socialize" });
                    areaColor = Color.magenta;
                    break;
                    
                case AreaType.Work:
                    availableActions.AddRange(new[] { "work", "meet", "study" });
                    areaColor = Color.gray;
                    break;
            }
        }
        
        /// <summary>
        /// 检查位置是否在区域内
        /// </summary>
        public bool ContainsPosition(Vector3 position)
        {
            return bounds.Contains(position);
        }
        
        /// <summary>
        /// 获取到区域中心的距离
        /// </summary>
        public float GetDistanceToCenter(Vector3 position)
        {
            return Vector3.Distance(position, bounds.center);
        }
    }
    
    /// <summary>
    /// 区域类型枚举
    /// </summary>
    public enum AreaType
    {
        Commercial,      // 商业区
        Residential,     // 住宅区
        Outdoor,         // 户外区
        Entertainment,   // 娱乐区
        Work,           // 工作区
        Special         // 特殊区域
    }
}